package com.jingdianjichi.subject.service.impl;

import com.alibaba.fastjson.JSON;
import com.jingdianjichi.subject.common.entity.PageResult;
import com.jingdianjichi.subject.common.enums.IsDeletedFlagEnum;
import com.jingdianjichi.subject.common.util.IdWorkerUtil;
import com.jingdianjichi.subject.common.util.LoginUtil;
import com.jingdianjichi.subject.convert.SubjecInfoConvert;
import com.jingdianjichi.subject.entity.SubjectInfoBO;
import com.jingdianjichi.subject.entity.SubjectOptionBO;
import com.jingdianjichi.subject.handle.subject.SubjectTypeHandleFactory;
import com.jingdianjichi.subject.handle.subject.SubjectTypeHandler;
import com.jingdianjichi.subject.infra.basic.entity.SubjectInfo;
import com.jingdianjichi.subject.infra.basic.entity.SubjectInfoEs;
import com.jingdianjichi.subject.infra.basic.entity.SubjectLabel;
import com.jingdianjichi.subject.infra.basic.entity.SubjectMapping;
import com.jingdianjichi.subject.infra.basic.service.SubjectEsService;
import com.jingdianjichi.subject.infra.basic.service.SubjectInfoService;
import com.jingdianjichi.subject.infra.basic.service.SubjectLabelService;
import com.jingdianjichi.subject.infra.basic.service.SubjectMappingService;
import com.jingdianjichi.subject.infra.entity.UserInfo;
import com.jingdianjichi.subject.infra.rpc.UserRpc;
import com.jingdianjichi.subject.redis.RedisUtil;
import com.jingdianjichi.subject.service.SubjectInfoDomainService;
import com.jingdianjichi.subject.service.SubjectLikedDomainService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 董代恒
 * @version 1.0
 */
@Service
@Slf4j
public class SubjectInfoDomainServiceImpl implements SubjectInfoDomainService {

    @Resource
    private SubjectInfoService subjectInfoService;

    @Resource
    private SubjectMappingService subjectMappingService;

    //把工厂注入进来，让工厂来处理题目是单选还是多选...
    @Resource
    private SubjectTypeHandleFactory subjectTypeHandleFactory;

    @Resource
    private SubjectLabelService subjectLabelService;

    private static final String RANK_KEY = "subject_rank";
    @Resource
    private SubjectEsService subjectEsService;
    @Resource
    private SubjectLikedDomainService subjectLikedDomainService;
    @Resource
    private UserRpc userRpc;
    @Resource
    private RedisUtil redisUtil;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(SubjectInfoBO subjectInfoBO) {
        if (log.isInfoEnabled()) {
            log.info("SubjectInfoDomainServiceImpl.add.dto:{}", JSON.toJSONString(subjectInfoBO));
        }

        SubjectInfo subjectInfo = SubjecInfoConvert.INSTANCE.subjectInfoBOToSubjectInfo(subjectInfoBO);
        subjectInfo.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        subjectInfoService.insert(subjectInfo);

        SubjectTypeHandler subjectTypeHandler = subjectTypeHandleFactory.getSubjectTypeHandler(subjectInfoBO.getSubjectType());

        //谁调用add得看你subjecrType的值了----->题目类型 1单选 2多选 3判断 4简答
        subjectTypeHandler.add(subjectInfoBO);

        List<Long> categoryIds = subjectInfoBO.getCategoryIds();
        List<Long> labelIds = subjectInfoBO.getLabelIds();

        //需要给mapping表插入数据
        List<SubjectMapping> subjectMappingList = new LinkedList<>();


        categoryIds.forEach(categoryId -> {
            labelIds.forEach(labelId -> {
                SubjectMapping subjectMapping = new SubjectMapping();
                subjectMapping.setSubjectId(subjectInfo.getId());
                subjectMapping.setCategoryId(categoryId);
                subjectMapping.setLabelId(labelId);
                subjectMapping.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
                subjectMappingList.add(subjectMapping);
            });
        });

        subjectMappingService.batchInsert(subjectMappingList);
        //同步插入数据到es中
        SubjectInfoEs subjectInfoEs = new SubjectInfoEs();
        //雪花算法生成唯一id
        subjectInfoEs.setDocId(new IdWorkerUtil(1, 1, 1).nextId());
        subjectInfoEs.setSubjectId(subjectInfo.getId());
        subjectInfoEs.setSubjectAnswer(subjectInfoBO.getSubjectAnswer());
        subjectInfoEs.setCreateTime(new Date().getTime());
        subjectInfoEs.setCreateUser("鸡翅");
        subjectInfoEs.setSubjectName(subjectInfo.getSubjectName());
        subjectInfoEs.setSubjectType(subjectInfo.getSubjectType());

        subjectEsService.insert(subjectInfoEs);

        //讲新增的题目保存到zset里面
        Object o = redisUtil.addScore(RANK_KEY, LoginUtil.getLoginId(), 1);
        log.info("排行榜加入的数据o:{}", o);
    }

    /**
     * 查询题目列表
     *
     * @param subjectInfoBO
     * @return
     */
    @Override
    public PageResult<SubjectInfoBO> getSubjectPage(SubjectInfoBO subjectInfoBO) {
        PageResult<SubjectInfoBO> pageResult = new PageResult<>();
        pageResult.setPageNo(subjectInfoBO.getPageNo());
        pageResult.setPageSize(subjectInfoBO.getPageSize());
        int start = (subjectInfoBO.getPageNo() - 1) * subjectInfoBO.getPageSize();
        SubjectInfo subjectInfo = SubjecInfoConvert.INSTANCE.subjectInfoBOToSubjectInfo(subjectInfoBO);
        //TODO:这个查询后期完善
        int count = subjectInfoService.countByCondition(subjectInfo, subjectInfoBO.getCategoryId(), subjectInfoBO.getLabelId());
        if (count == 0) {
            return pageResult;
        }

        List<SubjectInfo> subjectInfoList = subjectInfoService.queryPage(subjectInfo, subjectInfoBO.getCategoryId(), subjectInfoBO.getLabelId()
                , start, subjectInfoBO.getPageSize());
        List<SubjectInfoBO> subjectInfoBOS = SubjecInfoConvert.INSTANCE.subjectInfoListToSubjectInfoBOList(subjectInfoList);
        pageResult.setTotal(count);
        pageResult.setRecords(subjectInfoBOS);
        return pageResult;
    }

    /**
     * 查询题目详情
     *
     * @param subjectInfoBO
     * @return
     */
    @Override
    public SubjectInfoBO querySubjectInfo(SubjectInfoBO subjectInfoBO) {
        //1.根据题目id查询题目信息
        SubjectInfo subjectInfo = subjectInfoService.queryById(subjectInfoBO.getId());
        //2.获取题目类型
        Integer subjectType = subjectInfo.getSubjectType();

        SubjectTypeHandler handler = subjectTypeHandleFactory.getSubjectTypeHandler(subjectType);

        //
        SubjectOptionBO optionBO = handler.query(subjectInfo.getId());

        SubjectInfoBO bo = SubjecInfoConvert.INSTANCE.convertOptionAndInfoToBo(optionBO, subjectInfo);

        SubjectMapping subjectMapping = new SubjectMapping();

        subjectMapping.setSubjectId(subjectInfo.getId());
        subjectMapping.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());

        List<SubjectMapping> mappingList = subjectMappingService.queryLabelId(subjectMapping);

        List<Long> labelIdList = mappingList.stream().map(SubjectMapping::getLabelId).collect(Collectors.toList());
        List<SubjectLabel> labelList = subjectLabelService.batchQueryById(labelIdList);
        List<String> labelNameList = labelList.stream().map(SubjectLabel::getLabelName).collect(Collectors.toList());
        bo.setLabelName(labelNameList);

        bo.setLiked(subjectLikedDomainService.isLiked(subjectInfoBO.getId().toString(), LoginUtil.getLoginId()));
        bo.setLikedCount(subjectLikedDomainService.getLikedCount(subjectInfoBO.getId().toString()));
        assembleSubjectCursor(subjectInfoBO, bo);
        return bo;
    }

    private void assembleSubjectCursor(SubjectInfoBO subjectInfoBO, SubjectInfoBO bo) {
        Long categoryId = subjectInfoBO.getCategoryId();
        Long labelId = subjectInfoBO.getLabelId();
        Long subjectId = subjectInfoBO.getId();
        if (Objects.isNull(categoryId) || Objects.isNull(labelId)) {
            return;
        }
        Long nextSubjectId = subjectInfoService.querySubjectIdCursor(subjectId, categoryId, labelId, 1);
        bo.setNextSubjectId(nextSubjectId);
        Long lastSubjectId = subjectInfoService.querySubjectIdCursor(subjectId, categoryId, labelId, 0);
        bo.setLastSubjectId(lastSubjectId);
    }

    @Override
    public PageResult<SubjectInfoEs> getSubjectPageBySearch(SubjectInfoBO subjectInfoBO) {
        SubjectInfoEs subjectInfoEs = new SubjectInfoEs();
        subjectInfoEs.setPageNo(subjectInfoBO.getPageNo());
        subjectInfoEs.setPageSize(subjectInfoBO.getPageSize());
        subjectInfoEs.setKeyWord(subjectInfoBO.getKeyWord());
        return subjectEsService.querySubjectList(subjectInfoEs);
    }

    /**
     * 获取题目贡献榜
     *
     * @return
     */
    @Override
    public List<SubjectInfoBO> getContributeList() {
        //拿前五名做排行榜
        Set<ZSetOperations.TypedTuple<String>> typedTuples = redisUtil.rankWithScore(RANK_KEY, 0, 5);
        if (log.isInfoEnabled()) {
            log.info("getContributeList.typedTuples:{}", JSON.toJSONString(typedTuples));
        }
        // List<SubjectInfo> subjectInfoList = subjectInfoService.getContributeList();
        if (CollectionUtils.isEmpty(typedTuples)) {
            return Collections.emptyList();
        }
        //把List<SubjectInfo> 迁移到List<SubjectInfoBO>

        List<SubjectInfoBO> boList = new LinkedList<>();
        //数据库方式实现
        /*subjectInfoList.forEach(subjectInfo -> {
            SubjectInfoBO subjectInfoBO = new SubjectInfoBO();
            subjectInfoBO.setSubjectCount(subjectInfo.getSubjectCount());
            UserInfo userInfo = userRpc.getUserInfo(subjectInfo.getCreatedBy());
            subjectInfoBO.setCreateUser(userInfo.getNickName());
            subjectInfoBO.setCreateUserAvatar(userInfo.getAvatar());
            boList.add(subjectInfoBO);
        });*/
        //redis的zset实现
        typedTuples.forEach((rank -> {
            SubjectInfoBO subjectInfoBO = new SubjectInfoBO();
            //贡献题目的数量
            subjectInfoBO.setSubjectCount(rank.getScore().intValue());
            UserInfo userInfo = userRpc.getUserInfo(rank.getValue());
            //贡献人昵称
            subjectInfoBO.setCreateUser(userInfo.getNickName());
            //贡献题目人的头像
            subjectInfoBO.setCreateUserAvatar(userInfo.getAvatar());
            boList.add(subjectInfoBO);
        }));
        return boList;
    }
}
